import { NgZone } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { isString } from '../../util';
import { HttpService } from '../http/http.service';
import { I18nService } from '../i18n/i18n.service';
import { ApplicationEnv, RESOURCE_URL } from '../keys';
import { AclService } from '../service/acl.service';
import { BroadcastService } from '../service/broadcast.service';
import { DownloadService } from '../service/download.service';
import { IndexDbService } from '../service/index-db.service';
import { LoadingService } from '../service/loading.service';
import { LoggerService } from '../service/logger.service';
import { StoreService } from '../service/store.service';
import { Steve } from '../steve';


export class Base<U, B, S> {
  /** 保证当前系统运行的最小的数据集 */
  baseInfo: BaseInfo;
  /** 保存当前用户相关的数据 */
  currUser: any;
  /** 读取和设置离线数据 */
  storeService: StoreService<B, S>;
  /** 读取和设置离线数据 indexDB */
  indexDBService: IndexDbService;
  /** 发送请求 */
  httpService: HttpService<U>;
  /** 信息提示 */
  messageService: NzMessageService;
  /** 信息广播 */
  broadcastService: BroadcastService<B>;
  /** 控制加载中特效 */
  loadingService: LoadingService;
  /** 日志服务 */
  loggerService: LoggerService;
  /** 权限服务 */
  aclService: AclService<B, S>;
  /** i18n服务 */
  i18nService: I18nService;
  /** 路由跳转 */
  router: Router;
  /**
   * 下载文件
   */
  downloadService: DownloadService;

  url: U;

  ngZone: NgZone;

  /** 访问环境变量 */
  env: any;

  steve: Steve;

  /** 新的登录系统下公共请求头字段 */
  headers: any = {};

  private _privateKeys = ['_submitted', '_submitting', '_formComponentList'];

  constructor() {
    const injector = (<any>window)._moduleRef.injector;
    this.httpService = injector.get(HttpService);
    this.storeService = injector.get(StoreService);
    this.indexDBService = injector.get(IndexDbService);
    this.messageService = injector.get(NzMessageService);
    this.broadcastService = injector.get(BroadcastService);
    this.loadingService = injector.get(LoadingService);
    this.loggerService = injector.get(LoggerService);
    this.aclService = injector.get(AclService);
    this.i18nService = injector.get(I18nService);
    this.downloadService = injector.get(DownloadService);
    this.env = injector.get(ApplicationEnv);
    this.ngZone = injector.get(NgZone);
    this.router = injector.get(Router);
    this.url = injector.get(RESOURCE_URL);
    this.steve = (<any>window).steve;

    this.baseInfo = this.storeService.getItem(<any>'BaseInfo');
    this.currUser = this.storeService.getItem(<any>'User');

    // 监听 baseInfo 和 currUser 变化
    this.broadcastService.subscribe(<any>'StoreChange', (data) => {
      if (data.key === 'BaseInfo') {
        this.baseInfo = data.newValue;
      } else if (data.key === 'User') {
        this.currUser = data.newValue;
      }
    });
    try {
      const saasTenantCode = window.localStorage.getItem('ACE_CLI_SAAS_TENANT_CODE');
      const ACE_CLI_TOKEN = window.localStorage.getItem('ACE_CLI_TOKEN');
      const saasTenantToken = window.localStorage.getItem('ACE_CLI_SAAS_TENANT_TOKEN');

      this.headers = {
        'currentorgid': String(this.currUser.currentOrg.id),
        'saastenantcode': saasTenantCode,
        'saastenanttoken': saasTenantToken,
        'token': ACE_CLI_TOKEN,
        'loginname': this.currUser.user.loginName
      };
    } catch (error) {

    }
  }

  currPath(): string {
    return this.router.url.replace(/\?[\d\D]*/, '');
  }

  serializeData(data: any, removeKeys?: string[] | string): any {
    const removeRegexps = [];
    if (Array.isArray(removeKeys)) {
      removeRegexps.push(...removeKeys.filter(key => key.length > 0).map(key => new RegExp(key)));
    } else if (isString(removeKeys) && removeKeys.length > 0) {
      removeRegexps.push(new RegExp(removeKeys));
    }

    return JSON.parse(JSON.stringify(data, (key, value) => {
      if (typeof key === 'string') {
        const isRemove = removeRegexps.some(reg => reg.test(key));
        if (isRemove || this._privateKeys.includes(key)) {
          return undefined;
        } else if (typeof value === 'function') {
          return undefined;
        }
      } else {
        return undefined;
      }
      return value;
    }));
  }
}


/** 保证项目正常运行的必要信息 */
export interface BaseInfo {
  /** 项目名称 */
  name: string;
  /** 页面title */
  title: string;
  /** 项目logo地址 */
  logoUrl: string;
  /** 当前用户ID */
  userId: string;
  /** 当前用户名称 */
  userName: string;
  /** 当前用户头像地址 */
  avatarUrl?: string;
  /** 当前用户home地址 */
  homePath: string;
  /** 存储navTab列表的key */
  navTabStoreKey: string;
}
